﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Xml.Serialization;
using System.IO;
using brevis.Nop.SDK;
using brevis.Nop.SDK.Checker;
using brevis.Nop.SDK.Entity;
using brevis.Nop.SDK.ReportDataGetter;

namespace brevis.Nop.BusinessLogic.Data
{
    public class brevisNopDataMapper
    {
        /// <summary>
        /// Mapping to report entity object from report db object
        /// </summary>
        /// <param name="dbreport">Report (DB object)</param>
        public static NopReport MapToNopReport(Nop_Report dbreport)
        {
            try
            {
                var ser = new XmlSerializer(typeof(NopReport));
                var memStream = new MemoryStream();
                dbreport.Configuration.Save(memStream);
                memStream.Seek(0, SeekOrigin.Begin);
                var ret = (NopReport)ser.Deserialize(memStream);

                // create checker instances
                var checkerFactory = new InterfaceFactory<IChecker>();
                foreach (var sct in ret.Configuration.Check)
                {
                    sct.CheckerInstance = checkerFactory.Get(sct.Type);
                }

                // create parameter-/dataset-getter instances
                var paramDataGetterFactory = new InterfaceFactory<IReportDataGetter>();
                foreach (var cp in ret.Configuration.Parameter)
                {
                    // parameter getter
                    cp.DataGetterInstance = paramDataGetterFactory.Get(cp.DataGetterType);
                }
                foreach (var cds in ret.Configuration.DataSet)
                {
                    // dataset getter
                    cds.DataGetterInstance = paramDataGetterFactory.Get(cds.DataGetterType);
                }

                return ret;

            }
            catch (Exception err)
            {
                throw new Exception(
                    string.Format("Could not map to Report object! Please check inner exception"), 
                    err);

            }
        }
    }
}
